import React, { Component } from "react";
import ReactDOM from 'react-dom';
import { actions } from "mirrorx";
import queryString from 'query-string';
import { Switch, InputNumber,Loading, Table, Button, Col, Row, Icon, InputGroup, FormControl, Checkbox, Modal, Panel, PanelGroup, Label, Message } from "tinper-bee";
import Radio from 'bee-radio';
// import { BpmTaskApprovalWrap } from 'yyuap-bpm';
import Header from "components/Header";
import DatePicker from 'bee-datepicker';
// import RefMultipleTableWithInput from 'pap-refer/lib/ref-multiple-table/src/index';
// import 'pap-refer/lib/ref-multiple-table/src/index.css';
import {RefMultipleTableWithInput} from 'pap-refer/dist/index';
 import 'pap-refer/dist/index.css';
import Form from 'bee-form';
import Select from 'bee-select';
import moment from "moment";
import Viewer from 'react-viewer';
import './index.less';
import { setCookie, getCookie} from "utils";

const FormItem = Form.FormItem;
const Option = Select.Option;
const format = "YYYY-MM-DD HH:mm:ss";

class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            rowData: {},
            visibleView:false,
            imgList:[],
        }
    }
    async componentWillMount() {
        await actions.acceptancePaper.getOrderTypes();
        let searchObj = queryString.parse(this.props.location.search);
        let { btnFlag } = searchObj;
        if (btnFlag && btnFlag > 0) {
            let { search_id } = searchObj;
            let tempRowData = await actions.acceptancePaper.queryDetail({ search_id });
            let rowData = this.handleRefShow(tempRowData) || {};

            console.log('rowData',rowData);
            this.setState({
                rowData:rowData,
            })
        }

    }
    save = () => {//保存
        this.props.form.validateFields(async (err, values) => {
            values.attachment = this.state.fileNameData;
            let numArray = [
            ];
            for(let i=0,len=numArray.length; i<len; i++ ) {
                values[numArray[i]] = Number(values[numArray[i]]);
            }


            if (err) {
                Message.create({ content: '数据填写错误', color: 'danger' });
            } else {
                let {rowData,
                } = this.state;

                let saveObj = Object.assign({}, rowData, values);

                await actions.acceptancePaper.save(
                    saveObj,
                );
            }
        });
    }

    // 处理参照回显
    handleRefShow = (tempRowData) => {
        let rowData = {};
        if(tempRowData){

            let {
            } = tempRowData;

            this.setState({
            })
            rowData = Object.assign({},tempRowData,
                {
                }
            )
        }
        return rowData;
    }

    onBack = async() => {
        window.history.go(-1);
    }

    // 动态显示标题
    onChangeHead = (btnFlag) => {
        let titleArr = ["新增","编辑","详情"];
        return titleArr[btnFlag]||'详情';
    }

    // 跳转到流程图
    onClickToBPM = (rowData) => {
        console.log("actions", actions);
        actions.routing.push({
            pathname: 'acceptancePaper-chart',
            search: `?id=${rowData.id}`
        })
    }

    // 流程图相关回调函数
    onBpmStart = () => {
        actions.acceptancePaper.updateState({ showLoading: true });
    }
    onBpmEnd = () => {
        actions.acceptancePaper.updateState({ showLoading: false });
    }
    onBpmSuccess = () => {
          window.setTimeout(()=>{
                    actions.acceptancePaper.updateState({ showLoading: false });
                    // actions.routing.push('pagination-table');
                    actions.routing.goBack();
                },1000);
    }
    onBpmError = () => {
        actions.acceptancePaper.updateState({ showLoading: false });
    }

    // 审批面板展示
    showBpmComponent = (btnFlag, appType, id, processDefinitionId, processInstanceId, rowData) => {
        // btnFlag为2表示为详情
        if ((btnFlag == 2) && rowData && rowData['id']) {
            console.log("showBpmComponent", btnFlag)
            return (
                <div >
                    {/* {appType == 1 &&<BpmTaskApprovalWrap
                        id={rowData.id}
                        onBpmFlowClick={() => { this.onClickToBPM(rowData) }}
                        appType={appType}
                        onStart={this.onBpmStart}
                        onEnd={this.onBpmEnd}
                        onSuccess={this.onBpmSuccess}
                        onError={this.onBpmError}
                    />}
                    {appType == 2 &&<BpmTaskApprovalWrap
                        id={id}
                        processDefinitionId={processDefinitionId}
                        processInstanceId={processInstanceId}
                        onBpmFlowClick={() => { this.onClickToBPM(rowData) }}
                        appType={appType}
                        onStart={this.onBpmStart}
                        onEnd={this.onBpmEnd}
                        onSuccess={this.onBpmSuccess}
                        onError={this.onBpmError}
                    />} */}
                </div>

            );
        }
    }

    arryDeepClone = (array)=>{
        let result = [];
        if(array){
            array.map((item)=>{
                let temp = Object.assign([],item);
                result.push(temp);
            })
        }
    }

    renderImg = (imgUrls) => {
        let imgDom = [];
        let self = this;
        debugger;
        imgUrls && imgUrls.map(function(item) {
            imgDom.push(<img onClick={() => {self.showView(imgUrls)}}  src={item} />);
        })
        return <div className="edit-img-wraper">{imgDom}</div>
        
    }

    showView = (data) => {
        this.setState({
            visibleView:true,
            imgList:data
        })
    }

    initValueString = (name,pk) => {
        let param = {
            refname:name,
            refpk:pk
        }

        return JSON.stringify(param);
    }

    // 通过search_id查询数据

    render() {
        const self = this;

        let { btnFlag,appType, id, processDefinitionId, processInstanceId } = queryString.parse(this.props.location.search);
        btnFlag = Number(btnFlag);
        let {rowData,
            visibleView,
            imgList
        } = this.state;
        // 将boolean类型数据转化为string
        Object.keys(rowData).forEach(function(item){
            if(typeof rowData[item] === 'boolean'){
                rowData[item] = String(rowData[item]);
            }
        });


        let title = this.onChangeHead(btnFlag);
        let { 
            inspector,
            inspectorName,
            serialNo,
            goodsName,
            materialVariety,
            qualityGrade,
            unit,
            waterRatioMeter,
            waterRatioArtificial,
            buckleWaterWeight,
            impurityRatio,
            impurityWeight,
            returnGoods,
            returnGoodsReason,
            isReinspection,
            modifyuser,
            auditor,
            modifierReason,
            checkPoint,
            inspectorTime,
            checkPointName,
            imgUrls,
            heapNo,
            heapName,
            pk_material,
            
            unpackNo
         } = rowData;
        const { getFieldProps, getFieldError } = this.props.form;

        return (
            <div className='acceptancePaper-detail'>
                <Loading
                    showBackDrop={true}
                    loadingType="line"
                    show={this.props.showLoading}
                />
                <Header title={title} back={true} backFn={this.onBack}>
                    {(btnFlag < 2) ? (
                        <div className='head-btn'>
                            <Button className='head-cancel' onClick={this.onBack}>取消</Button>
                            <Button className='head-save' onClick={this.save}>保存</Button>
                        </div>
                    ) : ''}
                </Header>
                {
                    self.showBpmComponent(btnFlag, appType ? appType : "1", id, processDefinitionId, processInstanceId, rowData)
                }
                <Row className='detail-body'>
                    <h4>基础信息</h4>
                    <Col md={4} xs={6}>
                            <Label>
                                检验员：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('inspectorName', {
                                        validateTrigger: 'onBlur',
                                        initialValue: inspectorName || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('inspectorName')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                检验时间：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('inspectorTime', {
                                        validateTrigger: 'onBlur',
                                        initialValue: inspectorTime || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('inspectorTime')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                序列号：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('serialNo', {
                                        validateTrigger: 'onBlur',
                                        initialValue: serialNo || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('serialNo')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                货物名称：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('goodsName', {
                                        validateTrigger: 'onBlur',
                                        initialValue: goodsName || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('goodsName')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                物料品种：
                            </Label>
                                <RefMultipleTableWithInput
                                        disabled = {true}
                                        title={'物料'}

                                        param={{
                                            "id": "物料",

                                        }}
                                        refModelUrl={{
                                            tableBodyUrl: '/jxzy/materialref/blobRefSearch',//表体请求
                                            refInfo: '/jxzy/materialref/getRefModelInfo',//表头请求
                                        }}
                                        matchUrl='/pap_basedoc/common-ref/matchPKRefJSON'
                                        filterUrl='/pap_basedoc/common-ref/filterRefJSON'
                                        multiple={true}
                                        searchable={true}
                                        checkStrictly= {true}
                                        strictMode = {true}
                                        
                                        miniSearch={false}
                                        displayField='{refname}'
                                        valueField='refid'

                                        {...getFieldProps('materialVarietyCode', {
                                            initialValue: self.initValueString(materialVariety,pk_material),
                                        })}
                                    />

                            <span className='error'>
                                {getFieldError('materialVariety')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                质量等级：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('qualityGrade', {
                                        validateTrigger: 'onBlur',
                                        initialValue: qualityGrade || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('qualityGrade')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                单价(元)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('unit', {
                                        validateTrigger: 'onBlur',
                                        initialValue: unit || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('unit')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                含水分比-测水仪(%)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('waterRatioMeter', {
                                        validateTrigger: 'onBlur',
                                        initialValue: waterRatioMeter || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('waterRatioMeter')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                含水分比-人工(%)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('waterRatioArtificial', {
                                        validateTrigger: 'onBlur',
                                        initialValue: waterRatioArtificial || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('waterRatioArtificial')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                扣水分重(吨)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('buckleWaterWeight', {
                                        validateTrigger: 'onBlur',
                                        initialValue: buckleWaterWeight || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('buckleWaterWeight')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                含杂质比(%)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('impurityRatio', {
                                        validateTrigger: 'onBlur',
                                        initialValue: impurityRatio || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('impurityRatio')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                扣杂质重(吨)：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('impurityWeight', {
                                        validateTrigger: 'onBlur',
                                        initialValue: impurityWeight || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('impurityWeight')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                退货：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('returnGoods', {
                                        validateTrigger: 'onBlur',
                                        initialValue: returnGoods || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('returnGoods')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                退货原因：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('returnGoodsReason', {
                                        validateTrigger: 'onBlur',
                                        initialValue: returnGoodsReason || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('returnGoodsReason')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                是否重检：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('isReinspection', {
                                        validateTrigger: 'onBlur',
                                        initialValue: isReinspection || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('isReinspection')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                修改人：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('modifyuser', {
                                        validateTrigger: 'onBlur',
                                        initialValue: modifyuser || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('modifyuser')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                审核人：
                            </Label>
                                <FormControl disabled={btnFlag == 2 || false}
                                    {
                                    ...getFieldProps('auditor', {
                                        validateTrigger: 'onBlur',
                                        initialValue: auditor || '',
                                        rules: [{
                                            type:'string', message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('auditor')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                重检原因：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('modifierReason', {
                                        validateTrigger: 'onBlur',
                                        initialValue: modifierReason || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('modifierReason')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                检验点：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('checkPointName', {
                                        validateTrigger: 'onBlur',
                                        initialValue: checkPointName || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('checkPointName')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                开包件数：
                            </Label>
                                <FormControl disabled={btnFlag == 2||false}
                                    {
                                    ...getFieldProps('unpackNo', {
                                        validateTrigger: 'onBlur',
                                        initialValue: unpackNo || '',
                                        rules: [{
                                            type:'string',required: true,pattern:/\S+/ig, message: '请输入',
                                        }],
                                    }
                                    )}
                                />

                            <span className='error'>
                                {getFieldError('unpackNo')}
                            </span>
                        </Col>
                        <Col md={4} xs={6}>
                            <Label>
                                堆号：
                            </Label>
                                <RefMultipleTableWithInput
                                    disabled={btnFlag == 2||false}
                                    title={'堆号'}

                                    param={{
                                        "id": "堆号",

                                    }}
                                    refModelUrl={{
                                        tableBodyUrl: '/jxzy/rackref/blobRefSearch',//表体请求
                                        refInfo: '/jxzy/rackref/getRefModelInfo',//表头请求
                                    }}
                                    matchUrl='/pap_basedoc/common-ref/matchPKRefJSON'
                                    filterUrl='/pap_basedoc/common-ref/filterRefJSON'
                                    multiple={false}
                                    searchable={true}
                                    checkStrictly= {true}
                                    strictMode = {true}
                                    
                                    miniSearch={false}
                                    displayField='{refname}'
                                    valueField='refid'

                                    {...getFieldProps('heapNocode', {
                                        initialValue: self.initValueString(heapName,heapNo),
                                    })}
                                />
                                <span className='error'>
                                    {getFieldError('heapNo')}
                                </span>
                            
                        </Col>
                        <Col md={12}><h4>检验照片</h4></Col>
                        
                        {this.renderImg(imgUrls)}

                        <Viewer
                            visible={visibleView}
                            onClose={() => { this.setState({ visibleView: false }); } }
                            images={imgList.map((li) => {
                                return {
                                    src: `${li}`
                                }
                            }) }
                        />

                </Row>


            </div>
        )
    }
}

export default Form.createForm()(Edit);
